<template>
  <div id="app">
    <div id="map"></div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import Map from "ol/Map";
import View from "ol/View";
import ImageLayer from "ol/layer/Image";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import Feature from "ol/Feature";
import Polygon from "ol/geom/Polygon";
import ImageCanvasSource from "ol/source/ImageCanvas";
import Static from "ol/source/ImageStatic";
import WKT from "ol/format/WKT";
import GeoJSON from "ol/format/GeoJSON";

import { Fill, Stroke, Circle, Style } from "ol/style";
import axios from "axios";

import * as turf from "@turf/turf";

@Component({})
export default class App extends Vue {
  mounted() {
    this.initMap();
  }
  initMap() {
    function correct(coordinates: any) {
      const [[p1, p2, p3, p4]] = coordinates;
      let x = p4[0] - (p1[0] - p2[0]);
      let y = p4[1] - (p1[1] - p2[1]);
      return [[p1, p2, [x, y], p4, p1]];
    }
    var vLayer = new VectorLayer({
      source: new VectorSource({
        features: [],
      }),
    });
    var map = new Map({
      target: "map",
      view: new View({
        center: fromLonLat([84.925, 43.56], "EPSG:3857"),
        zoom: 6,
      }),
      layers: [
        new TileLayer({
          source: new XYZ({
            attributions:
              "© <a href='http://www.chinatoprs.com/' target='_blank'> 中测新图(北京)遥感技术有限责任公司 </a>",
            attributionsCollapsible: false,
            url:
              "http://t{0-7}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=ab1846502fcc2340e75c1d9ceb67c58b",
          }),
        }),
        vLayer,
      ],
    });

    axios.get("/data.json").then(async ({ data }: any) => {
      let { list } = data.data;
      list = list.filter((i: any) => i.flag);
      console.log(list.length);
      list = list.slice(0, 1);
      for (let item of list) await this.WktFormate(vLayer, map, item);
    });
  }

  addImageLayer(polygon: any, imageUrl: string, layerId: string, map: any) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.src = imageUrl;
      img.onload = function () {
        var imgLayer = new ImageLayer({ id: layerId });
        var imgSource = new ImageCanvasSource({
          ratio: 1,
          canvasFunction: (
            extent: any,
            resolution: any,
            ratio: any,
            size: any,
            Projection: any
          ) => {
            const exentTopLeft = [extent[0], extent[3]];
            const [xMIn, yMIn, xMax, yMax] = extent;

            const extentGeo = turf.polygon([
              [
                [xMIn, yMIn],
                [xMIn, yMax],
                [xMax, yMax],
                [xMax, yMIn],
                [xMIn, yMIn],
              ],
            ]);
            const m = JSON.parse(new GeoJSON().writeGeometry(polygon));
            const bool = turf.intersect(extentGeo, m);
            var canvas = document.createElement("canvas");
            canvas.setAttribute("width", size[0]);
            canvas.setAttribute("height", size[1]);
            var context: any = canvas.getContext("2d");

            if (!bool) return canvas;
            const [[p1, p2, p3, p4]] = polygon.getCoordinates();
            const [pxp1, pxp2, pxp3, pxp4] = [
              map.getPixelFromCoordinate(p1),
              map.getPixelFromCoordinate(p2),
              map.getPixelFromCoordinate(p3),
              map.getPixelFromCoordinate(p4),
            ];
            const pxExent = map.getPixelFromCoordinate(exentTopLeft);
            const tan1 = (p2[1] - p1[1]) / (p2[0] - p1[0]);
            const tan2 = (p4[0] - p1[0]) / (p4[1] - p1[1]);
            const p1Top2 = pxp2[0] - pxp1[0];
            const p1Top4 = pxp4[1] - pxp1[1];
            //   p1----p2
            //   /   /
            //  /   /
            // p4---p3
            context?.setTransform(
              1,
              -tan1,
              -tan2,
              1,
              pxp1[0] - pxExent[0],
              pxp1[1] - pxExent[1]
            );
            context?.drawImage(img, 0, 0, p1Top2, p1Top4);
            return canvas;
          },
        });
        imgLayer.setSource(imgSource);
        map.addLayer(imgLayer);
        resolve(true);
      };
      img.onerror = function () {
        resolve(false);
      };
    });
  }

  async WktFormate(vLayer: any, map: any, item: any) {
    const obj = item;

    obj["boundary"] = new WKT().readGeometry(obj.boundary, {
      dataProjection: "EPSG:4326",
      featureProjection: "EPSG:3857",
    });

    const newFe = new Feature({
      ...obj,
    });

    //

    newFe.setGeometryName("boundary");

    vLayer.getSource().addFeature(newFe);
    const url = "http://192.168.0.202:8081/quickView/" + obj.quickViewUrl;
    await this.addImageLayer(obj.boundary, url, obj.entityId + "", map);
  }
}
</script>

<style lang="less">
#map {
  height: calc(100vh - 70px);
  width: 80%;
}
</style>
